package com.qf.dao.impl;



import com.qf.dao.ReturnDao;
import com.qf.entity.BooksBorrow;
import com.qf.utils.DBUtils;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class ReturnDaoImpl implements ReturnDao {
    //展示借还表
    @Override
    public List<BooksBorrow> selectBorrowBook() throws SQLException {
        String sql="select bb.bbid,bc.reader,b.name,bb.borrow_date,bb.end_date,bb.return_date,b.state,bb.illegal from borrow_books bb " +
                "inner join books b on bb.book_id=b.bid inner join borrow_card bc on bb.card_id=bc.bcid inner join user u on bc.reader=u.uname";
        List<BooksBorrow> booksBorrowList = DBUtils.DB.qr.query(sql, new BeanListHandler<BooksBorrow>(BooksBorrow.class));
        return booksBorrowList;
    }
    //根据读者id和用户名查询
    @Override
    public BooksBorrow selectBorrowBookByIdAndName(Integer id,String name) throws SQLException {
        String sql="select bb.bbid,bc.reader,b.name,bb.borrow_date,bb.end_date,bb.return_date,b.state,bb.illegal from borrow_books bb " +
                "inner join books b on bb.book_id=b.bid inner join borrow_card bc on bb.card_id=bc.bcid " +
                " inner join user u on bc.reader=u.uname where bb.bbid=? and u.uname=?";
        BooksBorrow booksBorrow = DBUtils.DB.qr.query(sql, new BeanHandler<BooksBorrow>(BooksBorrow.class), id,name);
        return booksBorrow;
    }
    //还书
    @Override
    public int giveBackBook(Integer id, String name, String date,String illegal) throws SQLException {
        String sql="update (books b inner join borrow_books bb on b.bid=bb.book_id inner join borrow_card bc " +
                "on bb.card_id=bc.bcid inner join user u on bc.reader=u.uname)  set state=1,return_date=?,illegal=? " +
                "where bbid = ? and uname=? and return_date is null";
        Object[]objects={date,illegal,id,name};
        int num=DBUtils.DB.qr.update(sql,objects);
        System.out.println(num);
        return num;
    }
}
